package com.sky.Task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder() {
        log.info("开始处理订单支付超时,时间为:{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getTimeoutOrders(time);
        if (ordersList != null && !ordersList.isEmpty()) {
            for (Orders orders : ordersList) {
                orders.setCancelReason("订单支付超时");
                orderMapper.cancelByTimeOut(orders);
            }
        }
    }

    /**
     * 自动接单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processAutoConfirmOrder() {
        log.info("开始处理订单自动接单,时间为:{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-10);
        List<Orders> ordersList = orderMapper.getAutoConfirmOrders(time);
        if (ordersList != null && !ordersList.isEmpty()) {
            for (Orders orders : ordersList) {
                orderMapper.autoConfirm(orders);
            }
        }
    }

    /**
     * 处理订单派送中
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder() {
        log.info("开始处理订单派送中,时间为:{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getDeliveryOrders(time);
        if (ordersList != null && !ordersList.isEmpty()) {
            orderMapper.completeByDelivery(ordersList);
        }
    }
}
